from PIL import Image
import os
import cv2
import hashlib
from NasData import NasData
import shutil
from FmsCommon import FmsCommon
class InitNas():
    def __init__(self):
        fc =FmsCommon()
        self.my_dir_path_h  = fc.my_dir_path_h
        # current_file_path = os.path.abspath(
        #     globals().get('__file__', os.getcwd()))
        # self.my_dir_path = os.path.dirname(current_file_path)
        # print(current_file_path,self.my_dir_path+"/template/file.png")
        
        self.enum = {}
        self.enum["JPG"] = "图片"
        self.enum["JPEG"] = "图片"
        self.enum["PNG"] = "图片"
        self.enum["MP4"] = "视频"
        self.enum["3GP"] = "视频"
        # self.enum["MOV"] = "视频"
        # self.enum["AVI"] = "视频"
        #self.enum["WMV"] = "视频"
        self.enum["MPEG"] = "视频"
        
        self.enum["MP3"] = "音频"
        self.enum["WAV"] = "音频"
        self.enum["WMA"] = "音频"
        
        

    # 压缩视频文件
    def create_thumbnail_mp4(self, input_image_path, output_image_path):
        print("正在创建缩略图【视频】", input_image_path)
        video = cv2.VideoCapture(input_image_path)
        # 检查视频是否成功打开
        if not video.isOpened():
            print("Error: Could not open video.")
            exit()
        # 读取视频的帧率（FPS）和帧数
        # fps = video.get(cv2.CAP_PROP_FPS)
        frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
        for i in range(0, frame_count):
            # 读取一帧
            ret, frame = video.read()
            if ret:
                # 保存图片，例如保存为'frame_{}.jpg'
                # cv2.imwrite(output_image_path, frame)

                height, width = frame.shape[:2]
                re_im = cv2.resize(
                    frame, (280, int(height*280/width)), interpolation=cv2.INTER_LINEAR)
                cv2.imencode('.png', re_im)[1].tofile(output_image_path)

                break
            else:
                break
    # 压缩图片文件
    def create_thumbnail_pic(self, input_image_path, output_image_path, size=(280, 280)):
        print("正在创建缩略图【图片】", input_image_path,output_image_path)
        image = Image.open(input_image_path)
        
        image.thumbnail(size)
        image.save(output_image_path)
    def get_file_type(self, file_name):
        temps = file_name.split(".")
        enum = self.enum
        key = temps[-1].upper()
        if(enum.get(key) is None):
            return "其他"
        else:
            return enum[key]
    def create_raw(self,root,file):
        
        row_file = f"{root}\\_raw\\{file}.png"
        row_path = f"{root}\\_raw"
        file_path = f"{root}\\{file}"
        if not os.path.exists(row_file):

            if not os.path.exists(row_path):
                os.makedirs(row_path)
            file_type = self.get_file_type(file)
            item={}
            temps = file.split(".")
            key = temps[-1].lower()
            if file_type=="图片":
                self.create_thumbnail_pic(file_path,row_file)
                item["nas_abs_file_raw_path"] =os.path.abspath(row_file)
            elif  file_type=="视频":
                self.create_thumbnail_mp4(file_path,row_file)
                item["nas_abs_file_raw_path"] =os.path.abspath(row_file)
            elif  file_type=="音频":
                # other_file = self.my_dir_path+"/template/mp3.png"
                # shutil.copy(other_file, row_file)
                self.copy_thumbnail_pic(key,row_file)
                item["nas_abs_file_raw_path"] =os.path.abspath(row_file)
            else:
                
                
                # other_file = self.my_dir_path+"/template/file.png"
                # shutil.copy(other_file, row_file)
                self.copy_thumbnail_pic(key,row_file)

                item["nas_abs_file_raw_path"] =os.path.abspath(row_file)

            
            item["nas_abs_file_path"]= os.path.abspath(file_path)
            item["nas_file_type"]= file_type
            item["nas_file_md5"]= self.get_file_md5(f"{root}\\{file}")
            # item["nas_search_key"]= "temp"
            
            item["nas_abs_folder_path"]= root
            

            
            nData = NasData()
            nData.addNasInfo(item)
    def copy_thumbnail_pic(self,key,row_file):
        other_file = self.my_dir_path_h+f"/template/ext/{key}.png"
        if os.path.isfile(other_file):
            shutil.copy(other_file, row_file)
        else:
            other_file = self.my_dir_path_h+f"/template/ext/file.png"
            shutil.copy(other_file, row_file)

    def get_file_md5(self, file_path):
        with open(file_path, 'rb') as f:
            md5 = hashlib.md5()
            while True:
                data = f.read(4096)  # 每次读取4KB数据
                if not data:
                    break
                md5.update(data)
        return md5.hexdigest() 

    def main(self,folder_path):
        for root, dirs, files in os.walk(folder_path):
            if root.endswith("_raw") == False:
                for file in files:
                    
                    self.create_raw(root,file)
            
            

if __name__ == "__main__":
    
    iNas = InitNas()
    # iNas.main(r"E:\photo")
    iNas.create_thumbnail_mp4(r"e:\photo\Camera\VID_20141202_095438.3gp",r"e:\photo\Camera\_raw\VID_20141202_095438.3gp.png")